package main.cipher;

import org.json.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Base64;

public class TokenUtils {
    private static SecretKeySpec secretKey;
    private static byte[] key;
    private static String tokenScrect = "H8YU63R4GTVXV7Z1";

    /**
     * 作用：生成一个给客户端保存的token，这个token被cookie存储，用来判定用户。
     *
     * @param uuid
     * @return 返回一个JSON Object的字符串
     */
    public static String generateClientToken(String uuid) {
        // generate token for client
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String time = now.format(formatter);

        JSONObject tokenJson = new JSONObject();
        tokenJson.put("time", time);
        tokenJson.put("uuid", uuid);
        return TokenUtils.encrypt(tokenJson.toString());
    }

    /**
     * 解密一个token的字符串，成为一个JSON object
     * @param token
     * @return
     */
    public static JSONObject extractClientToken(String token) {
        String decrypted = TokenUtils.decrypt(token);
        JSONObject jo = new JSONObject(decrypted);
        return jo;
    }

    /**
     * 从一个合格的token中抓出UUID这个字段，UUID标识了一个唯一的用户
     * @param token
     * @return
     */
    public static String getUUIDFromToken(String token) {
        JSONObject jo = TokenUtils.extractClientToken(token);
        return (String) jo.get("uuid");
    }

    public static String encrypt(String strToEncrypt)
    {
        try
        {
            setKey(tokenScrect);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt)
    {
        try
        {
            setKey(tokenScrect);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        }
        catch (Exception e)
        {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }

    private static void setKey(String myKey)
    {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, "AES");
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
